import React, { useState } from 'react';
import { Input, Button, message, InputNumber } from 'antd';
import { Link } from 'react-router-dom';
import { ArrowLeftOutlined } from '@ant-design/icons';

const { TextArea } = Input;

const Base64Tool = () => {
  const [input1, setInput1] = useState('');
  const [input2, setInput2] = useState('');
  const [skipChars, setSkipChars] = useState(0);

  const handleEncode = () => {
    try {
      const encoded = btoa(unescape(encodeURIComponent(input1)));
      setInput2(encoded);
    } catch (e) {
      message.error('编码失败，请检查输入内容');
    }
  };

  const handleDecode = () => {
    try {
      const processedInput = input1.slice(skipChars);
      const decoded = decodeURIComponent(escape(atob(processedInput)));
      setInput2(decoded);
    } catch (e) {
      message.error('解码失败，请检查输入内容');
    }
  };

  const handleClear = () => {
    setInput1('');
    setInput2('');
    setSkipChars(0);
    message.success('已清空');
  };

  const handleCopy = (text) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('复制成功');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  return (
    <div className="tool-container">
      <div className="tool-header">
        <Link to="/" className="back-button">
          <ArrowLeftOutlined />
          返回工具箱
        </Link>
        <div className="tool-title">Base64 编解码工具</div>
      </div>
      
      <div className="tool-content">
        <div className="skip-chars-row">
          <span className="skip-chars-label">忽略前</span>
          <InputNumber
            min={0}
            value={skipChars}
            onChange={(value) => setSkipChars(value)}
            size="small"
            className="skip-chars-input"
          />
          <span className="skip-chars-label">个字符</span>
        </div>

        <div className="button-group">
          <Button onClick={handleEncode}>编码</Button>
          <Button onClick={handleDecode}>解码</Button>
          <Button onClick={handleClear}>清空</Button>
        </div>
        
        <div className="input-group">
          <div className="input-section">
            <TextArea
              value={input1}
              onChange={(e) => setInput1(e.target.value)}
              placeholder="在此输入文本"
              className="conversion-input"
            />
          </div>

          <div className="input-section">
            <TextArea
              value={input2}
              onChange={(e) => setInput2(e.target.value)}
              placeholder="在此输入文本"
              className="conversion-input"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Base64Tool;
